#!/usr/bin/env python
import os.path

__author__="Crabhi"
__version__ = "$Revision$"

import sys
import pygame
import helpers
import os.path
from pygame.locals import *

from error import FieldOccupied

class Namomi(object):
    """The Main PyMan Class - This class handles the main
    initialization and creating of the Game."""
    world_height = 15
    world_width = 20
    tile_size = 30
    framerate = 30
    margin_left = 10
    margin_top = 10
    selected = None

    def __init__(self, width=640,height=640):
        """Initialize PyGame"""
        pygame.init()
        """Set the window Size"""
        self.width = width
        self.height = height
        """Create the Screen"""
        self.screen = pygame.display.set_mode((self.width, self.height))
        # Prepare board:
        self.board = pygame.Surface((self.world_width * self.tile_size,
                                     self.world_height * self.tile_size))
        # load background image:
        try:
            bg_image = helpers.load_image("voda_%s.png" % self.tile_size)
            for i in range(self.world_height):
                for j in range(self.world_width):
                    self.board.blit(bg_image,(j*self.tile_size,i*self.tile_size))
        except pygame.error:
            self.board.fill((0,0,150))
        for i in range(self.world_height):
            pygame.draw.line(self.board, (0,0,0), (0, i * self.tile_size),
                        (self.world_width * self.tile_size, i * self.tile_size))
        for i in range(self.world_width):
            pygame.draw.line(self.board, (0,0,0), (i * self.tile_size, 0),
                        (i * self.tile_size, self.world_height * self.tile_size ))
        self.board.convert()
        # Not needed
        pygame.event.set_blocked(MOUSEMOTION)
        # Sprite group containing ships
        self.lode = pygame.sprite.Group()
        # self.pole is the representation of the game board
        self.pole = []
        for i in range(self.world_width):
            self.pole.append([])
            for j in range(self.world_height):
                self.pole[i].append(None)
        # Testing:
        self.add_ship(Destroyer(), (1,2))
        self.add_ship(Destroyer(), (2,3))
    
    def add_ship(self, ship, pos, orientation=None):
        """Add ship to a certain position"""
        if orientation is None:
            orientation = ship.orientation
        
        if not self.can_put_ship(ship, pos, orientation):
            raise FieldOccupied("Can't put ship on position %s" % str(pos))

        self.lode.add(ship)
        # Substract 2 to get the coords of the topleft of the ship
        ship.position = pos
        screenpos = self.coordinates_to_pixels((pos[0] -2, pos[1] - 2))
        ship.rect.top = screenpos[1]
        ship.rect.left = screenpos[0]
        
        # Update self.pole
        for i in range(5):
            for j in range(5):
                if ship.vzhled[j][i] != 0:
                    assert self.pole[i + pos[0] - 2][j + pos[1] - 2] is None, "FieldOccupied"
                    self.pole[i + pos[0] - 2][j + pos[1] - 2] = ship
    
    def can_put_ship(self, ship, pos, orientation=None):
        for i in range(5):
            for j in range(5):
                try:
                    if ship.vzhled[j][i] != 0 and self.pole[i + pos[0] - 2][j + pos[1] - 2] is not None:
                        return False
                except IndexError:
                    return False
        return True

    def coordinates_to_pixels(self, pos):
        """Change the board coordinate position to screen coordinates."""
        y = self.margin_top + self.tile_size * pos[1]
        x = self.margin_left + self.tile_size * pos[0]
        return x,y

    def pixels_to_coordinates(self, pos):
        x = pos[0] - self.margin_left
        y = pos[1] - self.margin_top
        x /= self.tile_size 
        y /= self.tile_size 
        return x, y

    def draw(self):
        self.screen.blit(self.board, (self.margin_left,self.margin_top)) 
        self.lode.draw(self.screen)
        # Highlight
        if self.selected is not None:
            pygame.draw.rect(self.screen, pygame.Color(255,255,255,100), self.selected.rect)

    def exit(self):
        pygame.quit()
        sys.exit(0)

    def handle_event_ingame(self, event):
        if event.type == QUIT:
            self.exit()
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                self.exit()
        elif event.type == MOUSEBUTTONDOWN:
            pos = self.pixels_to_coordinates(event.pos)
            try:
                self.selected = self.pole[pos[0]][pos[1]]
                print self.selected
            except IndexError:
                return
                
            if self.selected is not None:
                return
            try:
                self.add_ship(Destroyer(), pos)
            except FieldOccupied, e:
                print e
                return
        #elif event.type == MOUSEMOTION:
        #    self.myspos = event.pos
    def run(self):
        while True:
            self.draw()
            pygame.display.flip()
            self.handle_event_ingame(pygame.event.wait())


if __name__ == "__main__":
    Namomi().run()
